package com.heima.search.service.impl;

import com.heima.common.exception.CustException;
import com.heima.feigns.behavior.BehaviorFeign;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.HistorySearchDto;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.pojos.ApUserSearch;
import com.heima.search.service.ApUserSearchService;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class ApUserSearchServiceImpl implements ApUserSearchService {
    @Autowired
    MongoTemplate mongoTemplate;

    @Autowired
    BehaviorFeign behaviorFeign;
    /**
     * 保存用户搜索历史记录
     *
     * @param dto
     */
    @Override
    @Async("taskExecutor")
    public void insert(UserSearchDto dto) {
        //边界条件  行为实体不为空  ***没意义,
        /*Integer entryId = dto.getEntryId();
        if (entryId==0){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }*/
        ApBehaviorEntry behaviorEntry = behaviorFeign.findByUserIdOrEquipmentId(dto.getEntryId(), null);
        if (behaviorEntry==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        log.info("********************************* insert entryId:{}, searchWords:{}",dto.getEntryId(),dto.getSearchWords());

        //先查询再更新,有记录则更新时间，无记录则插入
        ApUserSearch userSearch = mongoTemplate.findOne(
                Query.query(
                        Criteria.where("entryId").is(dto.getEntryId())
                                .and("keyword").is(dto.getSearchWords())
                ),
                ApUserSearch.class
        );
        if (userSearch!=null){
            userSearch.setCreatedTime(new Date());
            mongoTemplate.save(userSearch);
            return;//更新则直接return
        }else {
            userSearch=ApUserSearch.builder()
                    .createdTime(new Date())
                    .entryId(dto.getEntryId())
                    .keyword(dto.getSearchWords())
                    .build();
        }
        //更新或插入
        mongoTemplate.save(userSearch);

        //插入则判断是否大于10条
        List<ApUserSearch> userSearches = mongoTemplate.find(
                Query.query(
                        Criteria.where("entryId").is(dto.getEntryId())
                ).with(Sort.by(Sort.Direction.ASC,"createdTime")),
                ApUserSearch.class
        );
        if (userSearches.size()>10){
            mongoTemplate.remove(userSearches.get(0));
        }
    }

    /**
     * 查询搜索历史  登录时才有
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findUserSearch(UserSearchDto dto) {
        //边界条件 需要登录
        List<ApUserSearch> userSearchList=new ArrayList<>();
        ApUser user = AppThreadLocalUtils.getUser();

        if (dto!=null && user!=null && user.getId()!=null){
            ApBehaviorEntry behaviorEntry = behaviorFeign.findByUserIdOrEquipmentId(user.getId(), null);
            if (behaviorEntry!=null){
                userSearchList= mongoTemplate.find(
                  Query.query(
                          Criteria.where("entryId").is(user.getId())
                  ).with(Sort.by(Sort.Direction.DESC,"createdTime")),
                  ApUserSearch.class
                );
            }
        }
        return ResponseResult.okResult(userSearchList);
    }

    /**
     * 删除搜索历史
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult delUserSearch(HistorySearchDto dto) {
        //边界条件  需登录 参数非空
        if (dto==null ||dto.getHistoryId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApUser user = AppThreadLocalUtils.getUser();
        if (user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //先查询再  更新历史记录
        mongoTemplate.remove(
                Query.query(
                        Criteria.where("entryId").is(user.getId())
                        .and("id").is(dto.getHistoryId())
                )
                ,ApUserSearch.class
        );
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}